package com.sinoglobal.ningxia.activity.vip;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.orhanobut.logger.Logger;
import com.sinoglobal.ningxia.R;
import com.sinoglobal.ningxia.activity.base.BaseActivity;
import com.sinoglobal.ningxia.beans.RootVo;
import com.sinoglobal.ningxia.beans.UserImageVo;
import com.sinoglobal.ningxia.beans.UserInfoVo;
import com.sinoglobal.ningxia.downdata.imp.RemoteImpl;
import com.sinoglobal.ningxia.frame.FlyApplication;
import com.sinoglobal.ningxia.http.Code;
import com.sinoglobal.ningxia.utils.Bimp;
import com.sinoglobal.ningxia.utils.BitmapUtiles;
import com.sinoglobal.ningxia.utils.ItktLog;
import com.sinoglobal.ningxia.utils.MContants;
import com.sinoglobal.ningxia.utils.SharedPreferenceUtil;
import com.sinoglobal.ningxia.utils.TextUtil;
import com.sinoglobal.ningxia.utils.UriUtils;
import com.sinoglobal.ningxia.utils.ValidUtil;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author limeishu
 * @createdate 2014-6-23 下午4:43:01
 * @Description: TODO(修改用户信息页面)
 */
public class UserInfoModify extends BaseActivity implements OnClickListener {
    // 昵称
    private EditText nickName, phoneNum, email;
    // 头像
    private ImageView photoImg;
    // 提交
    private Button submit;
    // 对话框
    private Dialog dialog;
    // 性别男、女
    private TextView male, female;
    // 手机号
    private String usernameStr;
    // 昵称字符串
    private String nicknameStr;
    // 性别
    private String sexStr;
    // 邮箱字符串
    private String emailStr;
    private Intent intent;
    // 屏幕宽度
    private int screenWidth;

    private RelativeLayout layout;

    private String imageName;
    // 拍照
    public static final int PHOTOHRAPH = 10;
    // 缩放
    public static final int PHOTOZOOM = 20;
    public static final String IMAGE_UNSPECIFIED = "image/*";
    protected static final int TEXT_MAX = 12;
    // 结果
    public static final int PHOTORESOULT = 30;
    // 返回个人中心页把 头像和 昵称带过去(头像是bitmap)
    private Bundle info;
    // 头像图片
    private Bitmap photoRound;
    private String picStr;
    // 服务器返回的图片地址
    private String url;
    private String localUrl;

    private CharSequence temp;
    private int selectionStart;
    private int selectionEnd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vip_modify_user_info);

        openChenJInShi();//开启沉浸式
        init();
        loadUserInfo();
        setOnClickListener();
    }

    private void setOnClickListener() {
        submit.setOnClickListener(this);
        photoImg.setOnClickListener(this);
        male.setOnClickListener(this);
        female.setOnClickListener(this);
    }

    // 提交更改信息
    private void submitUserInfo() {
        // 得到输入框的手机号
        usernameStr = phoneNum.getText().toString().trim();
        // 得到输入的邮箱
        emailStr = email.getText().toString().trim();
        // 得到哦啊输入的昵称
        nicknameStr = nickName.getText().toString().trim();
        try {
            String validNickname = ValidUtil.validNickName(nicknameStr);
            String validPhone = validPhone(usernameStr);
            String validEmail = ValidUtil.validEmail(emailStr);
            if (!MContants.EMPTY_STRING.equals(validNickname)) {
                return;
            }

            if (!MContants.EMPTY_STRING.equals(validPhone)) {
                showShortToastMessage(validPhone);
                return;
            }
            if (!MContants.EMPTY_STRING.equals(emailStr) && TextUtil.stringIsNotNull(validEmail)) {
                showShortToastMessage(validEmail);
                return;
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        new ItktAsyncTaskWithDialog<Void, Void, RootVo>(getResources().getString(R.string.sending), true, true) {

            @Override
            public RootVo before(Void... params) throws Exception {
                return RemoteImpl.getInstance().saveUserModifyInfo(FlyApplication.userId, usernameStr, nicknameStr, sexStr, emailStr);
            }

            @Override
            public void after(RootVo result) {
                if (null == result) { // 数据为空，显示reLoad
                    showReLoading();
                    return;
                }

                if (Code.CODE_SUCCESS != result.getCode()) {
                    showShortToastMessage(result.getMessage());
                    return;
                }
                SharedPreferenceUtil.saveString(FlyApplication.context, "sex", sexStr);
                SharedPreferenceUtil.saveString(FlyApplication.context, "username", usernameStr);
                SharedPreferenceUtil.saveString(FlyApplication.context, "nickname", nicknameStr);
                showShortToastMessage(getResources().getString(R.string.modify_success));
                finish();
            }

            @Override
            public void exception() {

            }
        }.execute();
    }

    private void init() {
        // 获取屏幕宽度
        titleView.setText(R.string.set_person_topstr);
        url = SharedPreferenceUtil.getString(FlyApplication.context, "photo");
        //FIXME 头像返回全路径 张杨 2014.10.29
        localUrl = url;
        submit = (Button) findViewById(R.id.btn_submit);
        nickName = (EditText) findViewById(R.id.edit_input_nickname);
        phoneNum = (EditText) findViewById(R.id.modify_edit_phone);
        email = (EditText) findViewById(R.id.modify_edit_email);
        photoImg = (ImageView) findViewById(R.id.setinfo_photo);
        info = new Bundle();
        intent = new Intent();
        male = (TextView) findViewById(R.id.radio_male);
        female = (TextView) findViewById(R.id.radio_female);
        try {
            loadPhoto(localUrl, photoImg);
        } catch (Exception e) {
            e.printStackTrace();
        }
        nickName.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                temp = s;
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                int count = 0;
                selectionStart = nickName.getSelectionStart();
                selectionEnd = nickName.getSelectionEnd();
                Pattern p = Pattern.compile("[\u4E00-\u9FA5]+");
                for (int i = 0; i < temp.length(); i++) {
                    String ss = temp.toString().substring(i, i + 1);
                    Matcher matcher = p.matcher(ss);
                    if (matcher.matches()) {
                        count = count + 1;
                    }
                }

                if (temp.toString().getBytes().length - count > TEXT_MAX) {
                    s.delete(selectionStart - 1, selectionEnd);
                    nickName.setText(s);
                    Toast.makeText(FlyApplication.context, "昵称不能超过12位", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }

    // 限制昵称字数的提示对话框
    public void showConfirmDialog() {
        if (dialog != null) {
            dialog.dismiss();
            dialog = null;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.inflate(R.layout.limit_nickname_dialog, null);
        Button confirm = (Button) view.findViewById(R.id.confirm_btn);
        builder.setView(view);
        builder.setCancelable(true);
        confirm.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog = builder.create();
        dialog.show();
    }

    @Override
    public void onClick(View v) {
        int nameLength = nickName.getText().toString().length();
        switch (v.getId()) {
            case R.id.btn_submit:

                if (nameLength > 12 || nameLength < 1) {
                    showConfirmDialog();
                    return;
                }
                submitUserInfo();
                break;
            case R.id.setinfo_photo:
                if (AndPermission.hasPermission(this, Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                    //需要权限READ_PHONE_STATE
                    showModifyPhotoDialog();
                } else {
                    AndPermission.with(this)
                            .requestCode(1001)
                            .permission(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE)
                            .send();
                }
                break;
            case R.id.tv_take_picture:
                takePhotoes();
                dialog.dismiss();
                break;
            case R.id.tv_gallery:
                setFromPhotoes();
                dialog.dismiss();
                break;
            case R.id.tv_cancel:
                dialog.dismiss();
                break;
            case R.id.radio_male:
                male.setTextColor(this.getResources().getColor(R.color.male_select));
                female.setTextColor(this.getResources().getColor(R.color.gray_hs));
                sexStr = "1";
                break;
            case R.id.radio_female:
                female.setTextColor(this.getResources().getColor(R.color.female_select));
                male.setTextColor(this.getResources().getColor(R.color.gray_hs));
                sexStr = "2";
                break;
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        // 只需要调用这一句，第一个参数是当前Acitivity/Fragment，回调方法写在当前Activity/Framgent。
        AndPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    // 成功回调的方法，用注解即可，里面的数字是请求时的requestCode。
    @PermissionYes(1001)
    private void getLocationYes(List<String> grantedPermissions) {
        // TODO 申请权限成功。
        showModifyPhotoDialog();
    }

    // 失败回调的方法，用注解即可，里面的数字是请求时的requestCode。
    @PermissionNo(1001)
    private void getLocationNo(List<String> deniedPermissions) {
        // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
        if (AndPermission.hasAlwaysDeniedPermission(this, deniedPermissions)) {
            // 第一种：用默认的提示语。
            AndPermission.defaultSettingDialog(this, 1001).show();
        }
    }

    // 拍照
    public void takePhotoes() {
        imageName = "/" + getStringToday() + ".jpg";

        // 调用系统的拍照功能
        Intent mIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Uri mUri;
        if (Build.VERSION.SDK_INT >= 24) {
            //如果是7.0或以上，使用getUriForFile()获取文件的Uri
            mUri = FileProvider.getUriForFile(this, "com.sinoglobal.ningxia" + ".fileprovider", new File(Environment.getExternalStorageDirectory(), imageName));
        } else {
            mUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), imageName));
        }

        mIntent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);


        startActivityForResult(mIntent, PHOTOHRAPH);

    }

    // 选择头像图片，拍照或者从相册中选择
    protected void showModifyPhotoDialog() {
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        screenWidth = dm.widthPixels;
        // 布局文件转换为view对象
        LayoutInflater inflater = LayoutInflater.from(this);
        dialog = new AlertDialog.Builder(UserInfoModify.this, R.style.DialogStyleBottom).create();
        dialog.show();

        dialog.getWindow().setGravity(Gravity.BOTTOM);
        LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = screenWidth; // 设置宽度
        dialog.getWindow().setAttributes(lp);
        dialog.getWindow().setWindowAnimations(R.style.persondialog);
        layout = (RelativeLayout) inflater.inflate(R.layout.change_photo_dialog, null);
        TextView btPicture = (TextView) layout.findViewById(R.id.tv_take_picture);
        TextView btGallery = (TextView) layout.findViewById(R.id.tv_gallery);
        TextView btCancel = (TextView) layout.findViewById(R.id.tv_cancel);

        btPicture.setOnClickListener(this);
        btGallery.setOnClickListener(this);
        btCancel.setOnClickListener(this);
        dialog.getWindow().setContentView(layout);
    }

    // 得到今天的拍照日期
    @SuppressLint("SimpleDateFormat")
    public static String getStringToday() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    // 从相册中选择图片
    public void setFromPhotoes() {
        // 调用系统的相册
        Intent tIntent = new Intent(Intent.ACTION_PICK, null);
        tIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_UNSPECIFIED);
        // 调用剪切功能
        startActivityForResult(tIntent, PHOTOZOOM);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null && requestCode != PHOTOHRAPH) {
            return;
        } else if (requestCode != PHOTOHRAPH && requestCode != PHOTOZOOM && requestCode != PHOTORESOULT) {
        }

        switch (requestCode) {
            case PHOTOHRAPH:
                // 拍照, 设置文件保存路径,这里放在跟目录下
                File picture = new File(Environment.getExternalStorageDirectory() + imageName);
                Uri imgUri = null;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    //如果是7.0或以上
                    imgUri = UriUtils.getImageContentUri(UserInfoModify.this, picture);
                    Logger.i("拍照转换前URI:" + imgUri.toString());
                } else {
                    imgUri = Uri.fromFile(picture);
                }
                Logger.i("拍照URI:" + imgUri);
                startPhotoZoom(imgUri);
                break;
            case PHOTOZOOM:
                try {
                    startPhotoZoom(data.getData());
                } catch (Exception e) {
                    showShortToastMessage(getResources().getString(R.string.modify_photo_fail));
                    e.printStackTrace();
                }
                break;
            case PHOTORESOULT:
                if (data == null)
                    return;
                data.getData();
                Bundle extras = data.getExtras();
                if (extras != null) {
                    photoRound = extras.getParcelable("data");
//				photoRound = BitmapUtiles.toRoundBitmap(photoRound);// 将头像设置为圆形
                    photoImg.setImageBitmap(photoRound);
                    picStr = Bimp.uploadImgForBase64(photoRound);
                    info.putParcelable("pic", photoRound);
                    intent.putExtras(info);

                    // 这里上传图片base64码 获取url
                    new ItktAsyncTaskWithDialog<Void, Void, UserImageVo>(getResources().getString(R.string.sending), true, true) {

                        @Override
                        public UserImageVo before(Void... params) throws Exception {
                            return RemoteImpl.getInstance().uploadUserImage(FlyApplication.userId, picStr);
                        }

                        @Override
                        public void after(UserImageVo result) {
                            if (null == result) { // 数据为空，显示reLoad
                                return;
                            }
                            ItktLog.i("---->" + result.toString());
                            if (Code.CODE_SUCCESS != result.getCode()) {
                                showShortToastMessage(result.getMessage());
                                return;
                            }
                            String imageUrl = result.getImg();// 得到图片下载路径
                            ItktLog.i("---->" + imageUrl);
                            SharedPreferenceUtil.saveString(UserInfoModify.this, "photo", imageUrl);
                            updateImageToPhoto();
                        }

                        @Override
                        public void exception() {
                            dismissWaitingDialog();
                            showShortToastMessage(getResources().getString(R.string.no_connections));
                        }

                    }.execute();

                }
                break;

            default:
                break;
        }
    }

    // 更新头像
    protected void updateImageToPhoto() {
        if (FlyApplication.isShowPic) {
            photoImg.setImageBitmap(photoRound);
        } else {
            photoImg.setBackgroundResource(R.drawable.icon_my_defaulthead);
        }
    }

    // 调用startActivityResult，返回之后的回调函数
    public void startPhotoZoom(Uri uri) {
//        Intent intent = new Intent("com.android.camera.action.CROP");
//        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
//        intent.putExtra("crop", "true");
//        // aspectX aspectY 是宽高的比例
//        intent.putExtra("aspectX", 1);
//        intent.putExtra("aspectY", 1);
//        // outputX outputY 是裁剪图片宽高
//        intent.putExtra("outputX", 200);
//        intent.putExtra("outputY", 200);
//        intent.putExtra("return-data", true);
//        startActivityForResult(intent, PHOTORESOULT);

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);//自己使用Content Uri替换File Uri
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 180);
        intent.putExtra("outputY", 180);
        intent.putExtra("return-data", true);
//        intent.putExtra("scale", true);
//        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outputfile));//定义输出的File Uri
//        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
//        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, PHOTORESOULT);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // loadPhoto(localUrl, photoImg);// 下载并显示图片
    }

    // 下载并显示图片
    private void loadPhoto(final String imgUrl, final ImageView iv) {

        ItktAsyncTaskWithDialog<Void, Void, Bitmap> asyncTask = new ItktAsyncTaskWithDialog<Void, Void, Bitmap>("", false, false) {

            @Override
            public Bitmap before(Void... params) throws Exception {
                return BitmapUtiles.getNetBitmap(imgUrl, FlyApplication.context);
            }

            @Override
            public void after(Bitmap result) {
                if (result != null) {
                    FlyApplication.PhotoBitmap = result;
                    iv.setImageBitmap(BitmapUtiles.toRoundBitmap(result));
                }
            }

            @Override
            public void exception() {
            }
        };
        asyncTask.execute();

    }

    // 对手机号的验证，手机号可以为空，手机号格式必须正确
    private String validPhone(String phone) {
        String message = "";
        if (MContants.EMPTY_STRING.equals(phone)) {
            message = MContants.EMPTY_STRING;
        } else if (phone.length() > 0 && phone.length() < 11) {
            message = getResources().getString(R.string.phone_edit_hint);
        } else {
            String phoneRule = "^((14[0-9])|(13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$";
            Pattern p = Pattern.compile(phoneRule);
            Matcher match = p.matcher(phone);
            if (!match.matches()) {
                message = getResources().getString(R.string.input_right_phoneNum);
            }
        }
        return message;
    }

    // 获取用户的详细信息
    private void loadUserInfo() {
        new ItktAsyncTaskWithDialog<Void, Void, UserInfoVo>(getResources().getString(R.string.loading_personal_info), true, true) {

            @Override
            public UserInfoVo before(Void... params) throws Exception {
                return RemoteImpl.getInstance().getUserInfo(FlyApplication.userId);
            }

            @Override
            public void after(UserInfoVo result) {
                if (null == result) { // 数据为空，显示reLoad
                    return;
                }
                ItktLog.i("---->" + result.toString());
                if (Code.CODE_SUCCESS != result.getCode()) {
                    return;
                }
                if (!MContants.BAN_LOGIN_CODE.equals(result.getStatus())) {
                    showShortToastMessage(getResources().getString(R.string.ban_user_login) + FlyApplication.userId
                            + getResources().getString(R.string.login).trim());
                    return;
                }
                // 将获取的信息显示在UI上
                nickName.setText(result.getNickname());
                if (!MContants.EMPTY_STRING.equals(result.getNickname())) {
                    nickName.setSelection(result.getNickname().length());
                }

                if (String.valueOf(Code.CODE_MALE).equals(result.getSex())) {
                    male.setTextColor(getResources().getColor(R.color.male_select));
                } else if (String.valueOf(Code.CODE_FEMALE).equals(result.getSex())) {
                    female.setTextColor(getResources().getColor(R.color.female_select));
                }
                phoneNum.setText(result.getUsername());
                // 设置手机号码不可编辑
                phoneNum.setKeyListener(null);
                email.setText(result.getEmail());
            }

            @Override
            public void exception() {
                dismissWaitingDialog();
                showShortToastMessage(getResources().getString(R.string.loadFail));
            }

        }.execute();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        photoRound = null;
    }
}
